#ifndef __MY_DATA__
#define __MY_DATA__
#include<string>
#include<unordered_map>
#include<sstream>
#include"Util.hpp"
namespace cloud
{
	class DataManger//数据管理类
	{
	private:
		std::string _backup_file;
		std::unordered_map<std::string, std::string> _table;//建立文件与文件唯一标识符的映射表
	public:
		DataManger(const std::string &backup_file):_backup_file(backup_file)
		{
			InitLoad();
		}
		void Split(const std::string& str, const std::string& sep, std::vector<std::string>* array)//字符切割
		{
			int pos = 0, idx = 0;
			while (true)
			{
				pos = str.find(sep, idx);
				if (pos == std::string::npos)
					break;
				if (idx == pos)
				{
					idx = pos + sep.size();
					continue;
				}

				//abc abc abc
				std::string tmp = str.substr(idx, pos - idx);
				array->push_back(tmp);
				idx = pos + sep.size();
			}
			if (idx < str.size())
			{
				std::string tmp = str.substr(idx);
				array->push_back(tmp);
			}
		}
		bool Storage()
		{
			//获取所有的数据信息
			// 
			//将所有信息进行指定格式组织
			std::stringstream ss;
			for (auto& e : _table)
			{
				ss << e.first << "$" << e.second << "\n";
			}
			//持久化存储
			cloud::FileUtil fu(_backup_file);
			fu.SetContent(ss.str());
			return true;
		}
		bool InitLoad()//初始化加载
		{
			std::vector<std::string> array;
			cloud::FileUtil fu(_backup_file);
			if (fu.Exists() == false)
				return true;
			std::string body;
			fu.GetContent(&body);
			Split(body, "\n", &array);

			for (auto& e : array)
			{
				std::vector<std::string> tmp;
				Split(e, "$", &tmp);
				if (tmp.size() < 2)
					continue;
				_table[tmp[0]] = tmp[1];
			}
			return true;	
		}
		bool Insert(const std::string &filename,const std::string& etag)
		{
			_table[filename] = etag;
			Storage();
			return true;
		}
		bool Updata(const std::string& filename, const std::string& etag)
		{
			_table[filename] = etag;
			Storage();
			return true;
		}
		bool GetOneByKet(const std::string& key,std::string*str)
		{
			auto it = _table.find(key);
			if (it == _table.end())
			{
				return false;
			}
			*str = it->second;
			return true;
		}
	};
}
#endif //

